﻿using System;
using System.Runtime.InteropServices;
using System.IO;

namespace maranov.SymlinkManager.FilesystemLinks
{
    public partial class SymbolicLink
    {
        /// <summary>
        /// Creates a symbolic link.
        /// </summary>
        /// <param name="lpSymlinkFileName">
        /// The symbolic link to be created.
        /// </param>
        /// <param name="lpTargetFileName">
        /// The name of the target for the symbolic link to be created.
        /// If lpTargetFileName has a device name associated with it, the link is treated as an absolute link;
        /// otherwise, the link is treated as a relative link.
        /// </param>
        /// <param name="dwFlags">
        /// Indicates whether the link target, lpTargetFileName, is a directory.
        /// </param>
        /// <returns>
        /// If the function succeeds, the return value is nonzero.
        /// If the function fails, the return value is zero.
        /// To get extended error information, call GetLastError.
        /// </returns>
        [DllImport("Kernel32", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern bool CreateSymbolicLink(
            [In] string lpSymlinkFileName,
            [In] string lpTargetFileName,
            SymbolicLinkFlag dwFlags
            );

        /// <summary>
        /// Removes existing symbolic link.
        /// </summary>
        /// <param name="path">Path to the link.</param>
        public static void RemoveSymbolicLink(string path)
        {
            try
            {
                if (Directory.Exists(path))
                    Directory.Delete(path);
                else
                    File.Delete(path);
            }
            catch (IOException e)
            {
                throw new LinkRemovalException("Symbolic link removal failed.", e);
            }
        }
    }
}
